package com.shxy.rlzy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shxy.rlzy.entity.SalaryItem;
import com.shxy.rlzy.mapper.SalaryItemMapper;
import com.shxy.rlzy.mapper.SalaryTaskDepartMapper;
import com.shxy.rlzy.mapper.SalaryTaskMapper;
import com.shxy.rlzy.service.ISalaryItemService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tanhao
 * @since 2022-03-19
 */
@Service
public class SalaryItemServiceImpl extends ServiceImpl<SalaryItemMapper, SalaryItem> implements ISalaryItemService {
    @Autowired
    private SalaryItemMapper salaryItemMapper;

    @Override
    public List<SalaryItem> getTaskDepartItems(long taskDepartId) {
        List<Map<String, Object>> tdis = salaryItemMapper.getTaskDepartItems(taskDepartId);
        return tdis.stream().map(tdi -> {
            SalaryItem si = new SalaryItem();
            si.setId((Long) tdi.get("id"));
            si.setTaskDepartId((Long) tdi.get("task_depart_id"));
            si.setTaskId((Long) tdi.get("task_id"));
            si.setSalaryId((Long) tdi.get("salary_id"));
            si.setEmployeeName((String) tdi.get("name"));
            si.setEmployeeId((Long) tdi.get("employee_id"));
            si.setMonthMerit((Double) tdi.get("month_merit"));
            si.setStatu((Integer) tdi.get("statu"));
            return si;
        }).collect(Collectors.toList());
    }

    @Override
    @Transactional
    public int setBonusList(List<SalaryItem> salaryItems) {
        AtomicInteger n = new AtomicInteger();
        salaryItems.forEach(salaryItem -> {
            if(saveBonus(salaryItem.getId(), salaryItem.getMonthMerit())) {
                if(changeStatus(salaryItem.getId(), 3)) {
                    n.getAndIncrement();
                }
            }
        });
        return n.get();
    }

    @Override
    public boolean saveBonus(Long id, double bonus) {
        return salaryItemMapper.updateBonusById(id, bonus) > 0;
    }

    @Override
    public boolean changeStatus(Long id, int statu) {
        SalaryItem salaryItem = salaryItemMapper.selectById(id);
        // 如果该个人任务存在，且状态有变化
        if(salaryItem != null && salaryItem.getStatu() != statu) {
            salaryItemMapper.changeStatus(id, statu);   // 修改个人任务状态
            return true;
        }
        return false;
    }

    @Override
    public int countByDepartTaskId(Long taskId) {
        QueryWrapper<SalaryItem> qw = new QueryWrapper<>();
        qw.eq("task_depart_id", taskId);
        return count(qw);
    }
}
